#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：download_ftp_data_demo.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/6/20 上午8:15 
"""

import ftplib
import os
from pathlib import Path
import time


def list_files(ftp):
	try:
		file_list = ftp.nlst()
	except UnicodeDecodeError:
		# 处理无法解码的文件名或者直接忽略
		file_list = []
		print("Warning: Some filenames could not be decoded.")

	return file_list

def ftpDownload(host, port, user, password, LocalDir, RemoteDir):
	# host = r"10.188.28.164"
	# port = 21
	# user = "Administrator"
	# password = "MGb%NwT3rjPch59Y"
	# LocalDir = "data/FTP/%s" % curTime
	# RemoteDir = "D:/rzpc"
	ftp = ftplib.FTP(encoding="gbk")
	ftp.connect(host, port)
	ftp.login(user, password)
	DownloadFileTree(LocalDir, RemoteDir, ftp)
	ftp.close()
	print("文件下载完成")
	filePath = Path(LocalDir).rglob("test.xlsx")
	ftpFile = next(filePath)
	return ftpFile


# 下载单个文件
def DownloadFile(LocalFile, RemoteFile, ftp):
	file_handler = open(LocalFile, "wb")
	print(file_handler)
	ftp.retrbinary("RETR " + RemoteFile, file_handler.write)
	file_handler.close()
	return True


# 下载整个目录下的文件
def DownloadFileTree(LocalDir, RemoteDir, ftp):
	print("remoteDir:", RemoteDir)
	if not os.path.exists(LocalDir):
		os.makedirs(LocalDir)
	ftp.cwd(RemoteDir)
	# ftp.nlst()获取目录下的文件
	# RemoteNames = ftp.nlst(encoding='utf-8')
	RemoteNames = list_files(ftp)
	print("RemoteNames", RemoteNames)
	for file in RemoteNames:
		Local = os.path.join(LocalDir, file)
		print("正在下载", ftp.nlst(file))
		if file.find(".") == -1:
			if not os.path.exists(Local):
				os.makedirs(Local)
			DownloadFileTree(Local, file, ftp)
		else:
			DownloadFile(Local, file, ftp)
	ftp.cwd("..")
	return


if __name__ == "__main__":
	curTime = time.strftime("%Y-%m-%d_%H-%M")

	param_dict = {
		"host": r"10.188.28.164",
		"port": 21,
		"user": "Administrator",
		"password": "MGb%NwT3rjPch59Y",
		"LocalDir": "data/FTP/%s" % curTime,
		"RemoteDir": ".",
	}

	file = ftpDownload(**param_dict)
